package QianFeng06.BinaryTreeDemo;

/**
 * 二叉树三种遍历
 * 1.先序遍历：按照根节点->左子树->右子树的顺序访问二叉树
 * 2.中序遍历：按照左子树->根节点->右子树的顺序访问
 * 3.后序遍历：按照左子树->右子树-->根节点的顺序访问
**/
public class BinaryTree {

    private Node root;

    public void add(int data) {
        if (root == null) {
            root = new Node(data);
        } else {
            root.addNode(data);
        }
    }
    //输出节点
    public void print() {
        root.printNode();
    }

    private class Node {
        private int data;
        private Node left;//左节点
        private Node right;//右节点
        public Node(int data) {
            this.data = data;
        }

        //递归添加节点
        public void addNode(int data) {
            if (this.data > data) {
                if (this.left == null) {
                    this.left = new Node(data);
                } else {
                    this.left.addNode(data);
                }
            } else {
                if (this.right == null) {
                    this.right = new Node(data);
                } else {
                    this.right.addNode(data);
                }
            }
        }

        //中序遍历
        public void printNode() {
            if (this.left != null) {
                this.left.printNode();
            }
            System.out.print(this.data + "->");
            if (this.right != null) {
                this.right.printNode();
            }
        }
    }
}
